package org.dreamwork.jasmine2.web.controls;

import org.dreamwork.jasmine2.web.html.Table;
import org.dreamwork.jasmine2.web.html.TableRow;
import org.dreamwork.jasmine2.web.html.TableCell;
import org.dreamwork.jasmine2.web.IWebControl;
import org.dreamwork.jasmine2.engine.IPostbackHandler;
import org.dreamwork.jasmine2.engine.HttpContext;
import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.jasmine2.util.StringConverter;
import org.dreamwork.util.NameValueCollection;
import org.dreamwork.util.ResourceManager;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-7-28
 * Time: 2:36:31
 */
public class Pagging extends Table implements IPostbackHandler {
    private int totalRows;
    private int totalPages;
    private int pageSize = 10;
    private int pageNo = 1;

    private String disableCss, disableStyle = "color:#CCCCCC; cursor: default";
    private String enableCss, enableStyle = "color:blue; cursor: pointer";

    private ResourceManager res;

    public Pagging () {
        setAttribute ("cellpadding", "0");
        setAttribute ("cellspacing", "0");
        setAttribute ("width", "100%");
    }

    public int getTotalRows () {
        return totalRows;
    }

    public void setTotalRows (int totalRows) {
        this.totalRows = totalRows;
    }

    public int getTotalPages () {
        return totalPages;
    }

    public void setTotalPages (int totalPages) {
        this.totalPages = totalPages;
    }

    public int getPageSize () {
        return pageSize;
    }

    public void setPageSize (int pageSize) {
        this.pageSize = pageSize;
    }

    public int getPageNo () {
        return pageNo;
    }

    public void setPageNo (int pageNo) {
        this.pageNo = pageNo;
    }

    public String getDisableCss () {
        return disableCss;
    }

    public void setDisableCss (String disableCss) {
        this.disableCss = disableCss;
    }

    public String getDisableStyle () {
        return disableStyle;
    }

    public void setDisableStyle (String disableStyle) {
        this.disableStyle = disableStyle;
    }

    public String getEnableCss () {
        return enableCss;
    }

    public void setEnableCss (String enableCss) {
        this.enableCss = enableCss;
    }

    public String getEnableStyle () {
        return enableStyle;
    }

    public void setEnableStyle (String enableStyle) {
        this.enableStyle = enableStyle;
    }

    public void postbackData (NameValueCollection props) {
        String pageNoId = id + ".pageNo";
        String pageSizeId = id + ".pageSize";
        String s_page_no = props.getValue (pageNoId);
        String s_page_size = props.getValue (pageSizeId);

        try {
            pageNo = Integer.parseInt (s_page_no);
        } catch (Exception ex) {
            //
        }
        try {
            pageSize= Integer.parseInt (s_page_size);
        } catch (Exception ex) {
            //
        }
    }

    @Override
    public void onDataBind (Object sender) throws EventException {
//        String expression = dynamicAttributes.get ("totalRows");
        String expression = getDynamicAttribute ("totalRows");
        if (expression != null) {
            try {
                Object value = page.eval (expression);
                if (value != null) {
                    totalRows = (Integer) value;
                }
            } catch (Exception e) {
                e.printStackTrace ();
            }
        }
    }

    public void onPrerender (IWebControl sender, HttpContext context) throws EventException {
        res = ResourceManager.instance ("org.dreamwork.jasmine2.web.controls.Pagging", context.getRequest ().getLocale ());
        TableRow row = new TableRow ();
        addRow (row);
        calculateTotalPages ();
        row.addCell (buildLeftCell ());
        row.addCell (buildRightCell ());
    }

    private TableCell buildLeftCell () {
        TableCell left = new TableCell ();
        left.setAttribute ("align", "left");
        left.setAttribute ("nowarp", "nowarp");
        StringBuffer sb = new StringBuffer ();
        sb.append (res.getStringPattern ("pagging.total-rows", totalRows));
        sb.append (" ");
        String current = res.getStringPattern ("pagging.page-no", pageNo, totalPages);
        sb.append (current).append (' ');
        sb.append (res.getStringPattern ("pagging.page-size", pageSize));
        left.addControl (new Literal (sb));
        return left;
    }

    private TableCell buildRightCell () {
        TableCell right = new TableCell ();
        right.setAttribute ("align", "right");
        right.setAttribute ("nowarp", "nowarp");
        StringBuffer sb = new StringBuffer ();

        String first = res.getString ("pagging.first");
        String prev  = res.getString ("pagging.prev");
        String next  = res.getString ("pagging.next");
        String last  = res.getString ("pagging.last");

        if (pageNo == 1) {
            sb.append ("<span ");
            if (disableCss != null)
                sb.append ("class=\"").append (disableCss).append ("\"");
            else if (!StringConverter.isEmpty (disableStyle))
                sb.append ("style=\"").append (disableStyle).append ("\"");
            sb.append ('>').append (first).append ("</span> | \r\n");
            sb.append ("<span ");
            if (disableCss != null)
                sb.append ("class=\"").append (disableCss).append ("\"");
            else if (!StringConverter.isEmpty (disableStyle))
                sb.append ("style=\"").append (disableStyle).append ("\"");
            sb.append ('>').append (prev).append ("</span> | \r\n");
        } else {
            sb.append ("<span onclick=\"__jump('")
              .append (id)
              .append ("', 1)\" ");
            if (!StringConverter.isEmpty (enableCss))
                sb.append ("class=\"").append (enableCss).append ("\"");
            else if (!StringConverter.isEmpty (enableStyle))
                sb.append ("style=\"").append (enableStyle).append ("\"");
            else
                sb.append ("style=\"cursor:pointer\"");
            sb.append ('>').append (first).append ("</span> | \r\n");
            sb.append ("<span onclick=\"__jump('")
              .append (id).append ("', ")
              .append (pageNo - 1)
              .append (")\" ");
            if (!StringConverter.isEmpty (enableCss))
                sb.append ("class=\"").append (enableCss).append ("\"");
            else if (!StringConverter.isEmpty (enableStyle))
                sb.append ("style=\"").append (enableStyle).append ("\"");
            else
                sb.append ("style=\"cursor:pointer\"");
            sb.append ('>').append (prev).append ("</span> | \r\n");
        }
        if (pageNo == totalPages) {
            sb.append ("<span ");
            if (disableCss != null)
                sb.append ("class=\"").append (disableCss).append ("\"");
            else if (!StringConverter.isEmpty (disableStyle))
                sb.append ("style=\"").append (disableStyle).append ("\"");
            sb.append ('>').append (prev).append ("</span> | \r\n");
            sb.append ("<span ");
            if (disableCss != null)
                sb.append ("class=\"").append (disableCss).append ("\"");
            else if (!StringConverter.isEmpty (disableStyle))
                sb.append ("style=\"").append (disableStyle).append ("\"");
            sb.append ('>').append (last).append ("</span>\r\n");
        } else {
            sb.append ("<span onclick=\"__jump('")
              .append (id).append ("', ")
              .append (pageNo + 1)
              .append (")\"");
            if (!StringConverter.isEmpty (enableCss))
                sb.append ("class=\"").append (enableCss).append ("\"");
            else if (!StringConverter.isEmpty (enableStyle))
                sb.append ("style=\"").append (enableStyle).append ("\"");
            else
                sb.append ("style=\"cursor:pointer\"");
            sb.append ('>').append (next).append ("</span> | \r\n");
            sb.append ("<span onclick=\"__jump('")
              .append (id).append ("', ")
              .append (totalPages)
              .append (")\" ");
            if (!StringConverter.isEmpty (enableCss))
                sb.append ("class=\"").append (enableCss).append ("\"");
            else if (!StringConverter.isEmpty (enableStyle))
                sb.append ("style=\"").append (enableStyle).append ("\"");
            else
                sb.append ("style=\"cursor:pointer\"");
            sb.append ('>').append (last).append ("</sapn>\r\n");
        }
        String pageNoId = id + ".pageNo";
        String pageSizeId = id + ".pageSize";
        sb.append ("<input type='hidden' id='").append (pageNoId)
          .append ("' name='").append (pageNoId).append ("' value='")
          .append (pageNo).append ("'/>\r\n");
        sb.append ("<input type='hidden' id='").append (pageSizeId)
          .append ("' name='").append (pageSizeId).append ("' value='")
          .append (pageSize).append ("'/>");
        right.addControl (new Literal (sb));
        return right;
    }

    private void calculateTotalPages () {
        if (pageSize <= 0) pageSize = 10;
        if (pageNo <= 0) pageNo = 1;
        totalPages = totalRows / pageSize;
        if (totalRows % pageSize != 0) totalPages ++;
        if (totalPages == 0) totalPages ++;
    }

    @Override
    public void init () {
        super.init ();
        page.registerClientScriptBlock (InternalJS.class, InternalJS.PAGGING_JS);
    }
}